import { SubjectComponent } from "../core/subject";
import ReactNode from "./react_node";

const { ccclass, property } = cc._decorator;

@ccclass
export default class RadioGroup2 extends SubjectComponent {
    @property(cc.Node)
    root: cc.Node = null;
    @property(ReactNode)
    cursor: ReactNode = null;
    curInd = -1;

    clean() {
        this.root.destroyAllChildren();
        this.root.removeAllChildren();
        this.curInd = -1;
    }

    protected onLoad(): void {
        this.init();
    }
    addItem(node: cc.Node) {
        this.root.addChild(node);
        let ind = this.root.children.length - 1;
        node.on(cc.Node.EventType.TOUCH_END, () => {
            this.select(ind);
        }, this);
    }
    delItem(node: cc.Node) {
        let ind = this.node.children.findIndex(ele => ele === node);
        if (-1 !== ind) {
            this.node.children[ind].removeFromParent();
        }
    }
    init() {
        this.root.children.forEach((child, ind) => {
            child.on(cc.Node.EventType.TOUCH_END, () => {
                this.select(ind);
            }, this);
        })
    }
    select(ind: number, noEmit = false) {
        this.curInd = ind;
        this.cursor.setTarget(this.root.children[ind]);
        if (!noEmit) {
            this.emit("select", ind);
        }
    }
};